<template>
  <element-table border :column="column" :data="tableData" max-height="250">
    <template #default="scope">
      <el-button text type="primary" size="small" @click.prevent="deleteRow(scope.$index)">Remove</el-button>
    </template>
  </element-table>
  <el-button class="mt-4" style="width: 100%" @click="onAddItem">Add Item</el-button>
</template>

<script lang="ts" setup>
import { ref } from "vue";

const now = new Date();

const column = [
  {
    prop: "date",
    fixed: true,
    width: 150,
    label: "Date",
  },
  {
    prop: "name",
    label: "Name",
    width: 120,
  },
  {
    prop: "state",
    label: "State",
    width: 120,
  },
  {
    prop: "city",
    label: "City",
    width: 120,
  },
  {
    prop: "address",
    label: "Address",
    width: 360,
  },
  {
    prop: "zip",
    label: "Zip",
    width: 180,
  },
  {
    label: "Operations",
    fixed: "right",
    width: 120,
    slotName: "default",
  },
];

const tableData = ref([
  {
    date: "2016-05-01",
    name: "Tom",
    state: "California",
    city: "Los Angeles",
    address: "No. 189, Grove St, Los Angeles",
    zip: "CA 90036",
  },
  {
    date: "2016-05-02",
    name: "Tom",
    state: "California",
    city: "Los Angeles",
    address: "No. 189, Grove St, Los Angeles",
    zip: "CA 90036",
  },
  {
    date: "2016-05-03",
    name: "Tom",
    state: "California",
    city: "Los Angeles",
    address: "No. 189, Grove St, Los Angeles",
    zip: "CA 90036",
  },
]);

const deleteRow = (index: number) => {
  tableData.value.splice(index, 1);
};

const onAddItem = () => {
  now.setDate(now.getDate() + 1);
  tableData.value.push({
    date: formatDate(now, "yyyy-MM-dd")!,
    name: "Tom",
    state: "California",
    city: "Los Angeles",
    address: "No. 189, Grove St, Los Angeles",
    zip: "CA 90036",
  });
};

function formatDate(date: string | Date, fmt: string) {
  if (typeof date == "string") {
    return date;
  }

  if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";

  if (!date || date == null) return null;
  const o = {
    "M+": date.getMonth() + 1, // 月份
    "d+": date.getDate(), // 日
    "h+": date.getHours(), // 小时
    "m+": date.getMinutes(), // 分
    "s+": date.getSeconds(), // 秒
    "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, `${date.getFullYear()}`.slice(4 - RegExp.$1.length));
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const item = o[k as keyof typeof o]
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? String(item) : `00${item}`.slice(`${item}`.length)
      );
    }

  }
  return fmt;
}
</script>
